package com.moju.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*",initParams = @WebInitParam(name = "encode",value = "UTF-8"))
public class EncodingFilter implements Filter {

    String encode = null;

    public void init(FilterConfig config) throws ServletException {
        System.out.println("I am Encoding Filter ");

         encode = config.getInitParameter("encode");
        System.out.println("character： " + encode);

    }

    public void destroy() {
        System.out.println("destory 销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {


        System.out.println(encode+"==============================");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse)  response;

//        HttpSession session = req.getSession();
//
//        User user  = session.getAttribute("user");
//
//        if(user == null){
//            req.getRequestDispatcher("/login.jsp").forward(req,resp);
//        }



        req.setCharacterEncoding(encode);
        resp.setContentType("text/html;charset="+encode);

        chain.doFilter(request, response); //放行

    }
}
